<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <base href="/">
  <meta charset="utf-8">
  <link rel="stylesheet" href="profile/profile.css">
  <link rel="stylesheet" href="layui/css/layui.css">
  <link rel="stylesheet" href="fonts/iconfont.css">
  <style>
    /* 账号管理表单样式 */
    .profile-content .layui-form {
      background-color: #f9f9f9;
      padding: 20px;
      border: 1px solid #e0e0e0;
      border-radius: 5px;
      margin-bottom: 20px;
    }
    .profile-content .layui-form h2 {
      margin-bottom: 20px;
      color: #333;
    }
    .profile-content .layui-form-item {
      margin-bottom: 15px;
    }
    .profile-content .layui-form-label {
      width: 120px;
    }
    .profile-content .layui-input-inline {
      width: 200px;
    }
    /* 账号管理和修改密码按钮样式 */
    .custom-button {
      background-color: #009688;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 3px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    .custom-button:hover {
      background-color: #00796b;
    }
  </style>
  <title>个人中心</title>
</head>
<body>
<div class="top-bar tonglan">
  <div class="top-nav-wrapper w">
    <div class="top-nav-left">

    </div>
    <div class="top-nav-right">
      <ul>
          <li><a href="page/index">首页</a></li><span></span>
          <li><a href="page/orderConfirm">我的订单</a></li> <span></span>
          <li><a href="page/cart">购物车</a></li> <span></span>
          <li class="lists-title"><a href="page/profile">个人中心</a></li><span></span>
          <li>
            <a href="#" id="logoutLink">退出登录</a>
          </li>
      </ul>
    </div>
  </div>
</div>
</div>
<div class="tonglan nav-bar">
  <div class="w">
    <div class="nav-logo">
      <img src="images/LOGO_2.png" alt="">
    </div>
    <div class="menu-wrapper">
      <div class="menu-wrapper-left">
        <ul _id="categorylist">
          <li style="border-bottom: none;">
            <a href="page/index">首页</a>
          </li>

        </ul>
      </div>
      <div class="menu-wrapper-right">

      </div>
    </div>
  </div>
</div>

<div class="w">
  <div class="list-left">
    <ul class="list">
      <li>
        <h3>个人中心</h3>
      </li>
      <li class="show">
        <a href="javascript:" _box="profile" >账号管理</a>
      </li>
      <li>
        <a href="javascript:" _box="collection">我的收藏</a>
      </li>
      <li>
        <a href="javascript:" _box="evaluation">评价管理</a>
      </li>
      <li>
        <a href="javascript:" _box="address">收货地址</a>
      </li>
    </ul>
  </div>
  <div class="list-center" >
    <!-- 个人中心内容 -->
    <div class="profile-content show" _win="profile">
      <div class="layui-form" lay-filter="userinfo">
        <h2>个人账号管理</h2>
        <div class="layui-form-item">
          <div class="layui-input-inline">
            <img src="" id="userimg" style="height: 100px;width: 100px;cursor: pointer;">
            <input type="hidden"   name="imgurl" class="layui-input">
          </div>
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label">用户名</label>
          <div class="layui-input-inline">
            <input type="text"  name="username" placeholder="请输入用户名" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">电话</label>
          <div class="layui-input-inline">
            <input type="text"   name="phone" placeholder="请输入手机号" lay-verify="required|phone" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">年龄</label>
          <div class="layui-input-inline">
            <input type="text"   name="age" placeholder="请输入年龄" lay-verify="required|number" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">性别</label>
          <div class="layui-input-inline">
            <input type="radio" name="sex" value="男" title="男">
            <input type="radio" name="sex" value="女" title="女">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">邮箱</label>
          <div class="layui-input-inline">
            <input type="text" name="email" placeholder="请输入邮箱" lay-verify="email" class="layui-input">
          </div>
        </div>
        <button type="button" class="custom-button" lay-submit lay-filter="saveuser">提交</button>
      </div>
      <!-- 修改密码表单 -->
      <div class="layui-form" lay-filter="changepassword">
        <h2>修改密码</h2>
        <div class="layui-form-item">
          <label class="layui-form-label">旧密码</label>
          <div class="layui-input-inline">
            <input type="password" name="oldpassword" placeholder="请输入旧密码" lay-verify="required" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">新密码</label>
          <div class="layui-input-inline">
            <input type="password" name="newpassword" placeholder="请输入新密码" lay-verify="required" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">确认新密码</label>
          <div class="layui-input-inline">
            <input type="password" name="confirmpassword" placeholder="请再次输入新密码" lay-verify="required|compareTo[newpassword]" class="layui-input">
          </div>
        </div>
        <button type="button" class="custom-button" lay-submit lay-filter="changepwd">修改密码</button>
      </div>
    </div>


    <!-- 评价管理内容 -->
    <div class="profile-content" _win="evaluation">
      <h2>评价管理</h2>
      <div id="evaluation-list"></div>
    </div>
    <!-- 我的收藏内容 -->
    <div class="profile-content" _win="collection">
      <h2>我的收藏</h2>
      <div class="order_box" name="collectbox">

      </div>
    </div>

    <!-- 收货地址内容 -->
    <div class="profile-content" _win="address">
      <h2>收货地址</h2>
      <div class="order_box" name="addressbox">

      </div>
    </div>
  </div>
</div>
<iframe src="footer/footer.html" frameborder="0"></iframe>

<div style="display: none" id="addAddressWin" class="layui-form">
  <div class="layui-form-item">
    <label class="layui-form-label">地址名称</label>
    <div class="layui-input-inline">
      <input type="text" name="addressname" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">省份</label>
    <div class="layui-input-inline">
      <select name="provincecode" lay-filter="provincecode"></select>
      <input type="hidden" name="province">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">城市</label>
    <div class="layui-input-inline">
      <select name="citycode" lay-filter="citycode"></select>
      <input type="hidden" name="city">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">区划</label>
    <div class="layui-input-inline">
      <select name="areacode" lay-filter="areacode"></select>
      <input type="hidden" name="area">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">详细地址</label>
    <div class="layui-input-inline">
      <input type="text" name="address" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">联系人</label>
    <div class="layui-input-inline">
      <input type="text" name="name" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">电话</label>
    <div class="layui-input-inline">
      <input type="text" name="phone" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <button type="button" lay-submit lay-filter="addAddressBtn">提交</button>
  </div>
</div>

<script type="text/html" id="addressitem">
  <div class='order_box_in layui-form'>
    <div class='addressname' style="">

    </div>
    <div  style="margin-top:8px">
      地址:<span class="areatext"></span>
    </div>
    <div class='' style="margin-top:8px;">
      详细地址:<span class="addresstext"></span>
    </div>
    <div class='layui-row' style="margin-top:8px;">
      <div class=' layui-col-md6'>
        联系人:<span class="addrname"></span>
      </div>
      <div class=' layui-col-md6'>
        电话:<span class="addrphone"></span>
      </div>
    </div>
    <div  style="margin-top:8px" class="layui-row">
      <div class="layui-col-md6 clearfix">
        <input type='checkbox'  name="default" value="1"  _addrid=''  lay-filter="defaultAddress">
      </div>
      <div class="layui-col-md6 addressbtn" style="text-align: right;">
        <button type='button' _addrid name='edit' class="layui-btn layui-btn-sm layui-btn-radius layui-btn-normal">编辑</button>
        <button type='button' _addrid name='delete' class="layui-btn layui-btn-sm layui-btn-radius layui-btn-danger">删除</button>
      </div>
    </div>
  </div>
</script>
<script type="text/html" id="addAddress">
  <div class='order_box_in layui-form' addAddress style="text-align: center;line-height: 170px;font-size: 30px;cursor: pointer;">
    +
  </div>
</script>
<script type="text/html" id="collect-item-template">
  <div class="collect-item" data-productid="{{d.productid}}" style="cursor: pointer;">
    <img src="{{d.product.imgurl}}" alt="{{d.product.productname}}" class="collect-item-img">
    <div class="collect-item-info">
      <h3 class="collect-item-name">{{d.product.productname}}</h3>
      <p class="collect-item-price">价格: {{d.product.price}} 元</p>
      <p class="collect-item-category">商品类型: {{d.product.productcategory}}</p>
      <button class="collect-item-delete" data-productid="{{d.productid}}">取消收藏</button>
    </div>
  </div>
</script>

<script src="layui/layui.all.js"></script>
<script type="text/html" _id="categoryitem">
  <li>
    <a href="page/list"></a>
    <div>
      <ul class="menu-main w">

      </ul>
    </div>
  </li>
</script>
<script type="text/html" id="categorychild">
  <li>
    <a href="">
      <img src="" alt="">
      <span></span>
    </a>
  </li>
</script>
<script>
  //父级分类下拉二级分类事件
  const $ = layui.$;
  const form=layui.form;
  const upload=layui.upload;
  const layer=layui.layer;

  $.ajax({
    url: 'category/list',
    data: { id: -1 },
    beforeSend: function() {
      console.log("即将发送请求：category/list，请求参数：", { id: -1 });
    },
    success: function (result) {
      console.log("category/list 请求成功，响应信息：", result);
      let data = result.data;
      console.log(data);

      // 筛选出 pid 为 -1 的父级分类
      const parentCategories = data.filter(item => item.pid === -1);

      parentCategories.forEach((parent) => {
        let item = $('script[_id="categoryitem"]').text();
        let $item = $(item);
        $item.children("a").text(parent.categoryname);
        $item.children("a").attr("href", `page/list?category=${parent.categoryname}`);
        let $ul = $item.find("ul");

        // 发起请求获取子分类
        $.ajax({
          url: "category/getChildren",
          data: { id: parent.categoryid },
          success: function (res) {
            // 内层循环使用不同的变量名 j
            for (let j = 0; j < res.length; j++) {
              let childtext = $("#categorychild").text();
              let $child = $(childtext);
              $child.find("span").text(res[j].categoryname);
              $child.find("img").attr("src", res[j].imgurl);
              $child.find("a").attr("href", `page/list?category=${res[j].categoryname}`);
              $ul.append($child);
            }
          },
          error: function (error) {
            console.error(`获取 ${parent.categoryname} 的子分类失败:`, error);
          }
        });

        $('ul[_id="categorylist"]').append($item);
      });
    },
    error: function (error) {
      console.error('获取分类列表失败:', error);
    }
  });
//点击左侧组件  _box
  //在右侧显示对应的窗口信息  _win
  $("[_win]").hide();
  $("[_win]:first").show();
  showprofile();
  $(".list-left .list li a:first").addClass("active");
  // 为所有具有 _box 属性的链接绑定点击事件
  $(document).on('click', '[_box]', function () {
    // 移除所有侧边栏项的激活状态
    $(".list-left .list li a").removeClass("active");
    // 为当前点击的侧边栏项添加激活状态
    $(this).addClass("active");
    $("[_win]").hide();
    let val = $(this).attr("_box");
    if (val === 'profile') {
      showprofile();
    } else if (val === 'collection') {
      showCollection();
    } else if (val === 'evaluation') {
      showEvaluation();
    } else if (val === 'address') {
      showAddress();
    }
    $("[_win='" + val + "']").show();
  });


  function showprofile(){
    //查询用户数据
    $.ajax({
      url:'user/getuserinfo',
      success:function (result) {
        let data=result.data;
        let code=result.code;
        let msg=result.msg;
        if (code==401){
          layer.msg(msg,{icon: 2});
          setTimeout(function () {
            location.href="page/login";
          },2000);
        } else if (code!=200){
          layer.msg(msg,{icon:2});
        }else {
          //将用户数据显示到页面上
          form.val("userinfo",data);
          $("#userimg").attr("src", data.imgurl);
          // 选中对应的性别
          if (data.gender) {
            $(`input[name='gender'][value='${data.gender}']`).prop('checked', true);
            form.render('radio');
          }
        }
      }
    });
  }

  form.on("submit(saveuser)",function (obj) {
    let  formdata=obj.field;
    $.ajax({
      url:'user/edit',
      data:formdata,
      success:function (result) {
        console.log("save",result);
        if(result.code===200){
          layer.msg("保存成功",{icon:1,time:1800});
        }else{
          layer.msg(result.msg,{icon:2,time:1800});
        }
      },
      error: function (error) {
        layer.msg("保存失败，请稍后重试", { icon: 2, time: 1800 });
      }
    });
    return false;
  });
  upload.render({
    elem:"#userimg",
    url:"file/upload",
    done:function (res,index,upload) {
      layer.msg("上传成功",{icon:1,time:1800});
      let imgurl=res.data[0].src;
      $("#userimg").attr("src",imgurl);
      $("[name='imgurl']").val(imgurl);
    }
  });

  //修改密码
  form.verify({
    newpasswordCheck: function (value) {
      if (value.length < 6) {
        return '新密码长度不能少于 6 位';
      }
    }
  });
  form.on("submit(changepwd)", function (obj) {
    let formdata = obj.field;
    // 验证新密码和确认新密码是否一致
    if (formdata.newpassword!== formdata.confirmpassword) {
      layer.msg("新密码和确认新密码不一致，请重新输入", { icon: 2, time: 1800 });
      return false;
    }

    $.ajax({
      url: 'user/updatePassword',
      method: 'POST',
      data: formdata,
      success: function (result) {
        if (result.code === 200) {
          layer.msg("密码修改成功", { icon: 1, time: 1800 });
        } else {
          layer.msg(result.msg, { icon: 2, time: 1800 });
        }
      },
      error: function (error) {
        layer.msg("密码修改失败，请稍后重试", { icon: 2, time: 1800 });
      }
    });
    return false;
  });

  $("[name='addressbox']").on("click", "[addAddress]", function () {
    // 清空表单内容
    const formFields = [
      'addressname', 'provincecode', 'province', 'citycode', 'city',
      'areacode', 'area', 'address', 'name', 'phone'
    ];
    formFields.forEach(field => {
      $(`[name='${field}']`).val('');
    });
    // 重新渲染表单组件
    form.render();

    addAddressLayerIndex = layer.open({
      type: 1,
      area: ["400px", "600px"],
      content: $("#addAddressWin")
    });
  });


  showArea(100000,$("[name='provincecode']"));
  function showArea(code, $dom) {
    $.ajax({
      url: "https://restapi.amap.com/v3/config/district",
      data: {key: 'd5e466c74f37e2b1f89163a68a161ea7', keywords: code},
      success: function (result) {
        console.log("showArea",result);
        let children = result.districts[0].districts;
        $dom.empty();
        $dom.append($("<option value=''></option>"));
        for (let i = 0; i < children.length; i++) {
          $dom.append($("<option value='" + children[i].adcode + "'>" + children[i].name + "</option>"));
        }
        form.render("select");
      }
    });
  }

  form.on('select(provincecode)', function (data) {
    let provincecode = data.value; //得到被选中的值
    showArea(provincecode, $("[name='citycode']"));
    let provincename = $(data.othis).find("input").val();
    $("[name='province']").val(provincename);
  });
  form.on('select(citycode)', function (data) {
    let citycode = data.value; //得到被选中的值
    showArea(citycode, $("[name='areacode']"));
    let cityname = $(data.othis).find("input").val();
    $("[name='city']").val(cityname);
  });

  form.on('select(areacode)', function (data) {
    let areaname = $(data.othis).find("input").val();
    $("[name='area']").val(areaname);
  });

  
  //新增收货地址保存
  form.on("submit(addAddressBtn)",function (obj) {
    let formdata=obj.field;
    $.ajax({
      url:'address/add',
      data:formdata,
      success: function (result) {
        console.log("address/add",result);
        layer.msg("添加成功", { icon: 1, time: 1800 });
        // 关闭新增地址的对话框
        layer.close(addAddressLayerIndex);

        // 重新加载地址列表
        showAddress();
      },
      error: function (error) {
        layer.msg("添加失败，请稍后重试", { icon: 2, time: 1800 });
      }
    });
    return false;
  });

  showAddress();
  function showAddress(){
  $.ajax({
    url:"address/getaddressbyuserid",
    beforeSend: function() {
      console.log("即将发送请求：address/getaddressbyuserid");
    },
    success:function (result){
      console.log("获取地址信息响应：", result);
       let data=result.data;
      let addressBox = $("[name='addressbox']");
      addressBox.empty();
       for (let i=0;i<data.length;i++){
         let itemtext=$("#addressitem").text();
         let $item=$(itemtext);
         $item.find("[type='checkbox']").attr("_addrid", data[i].addressid).prop("checked", data[i].isdefault == 1);
         $item.find(".addressname").text(data[i].addressname);
         $item.find(".areatext").text(data[i].province+"-"+data[i].city+"-"+data[i].area);
         $item.find(".addresstext").text(data[i].address);
         $item.find(".addrname").text(data[i].name);
         $item.find(".addrphone").text(data[i].phone);
         if (data[i].isdefault==1){
           $item.find("[type='checkbox']").prop("checked", true);
       }
         $item.find("button[name='edit']").attr("_addrid", data[i].addressid);
         $item.find("button[name='delete']").attr("_addrid", data[i].addressid);
         //删除事件
         $item.find("button[name='delete']").on('click', function() {
           const addressid = $(this).attr("_addrid");
           layer.confirm('确定要删除该地址吗？', {
             icon: 3,
             title: '确认删除'
           }, function(index) {
             $.ajax({
               url: 'address/delete',
               data: { id: addressid },
               success: function(response) {
                 console.log("delete",response);
                 if (response.code === 200) {
                   layer.msg("删除成功", { icon: 1, time: 1800 });
                   showAddress(); // 刷新地址列表
                 } else {
                   layer.msg("删除失败，请稍后重试", { icon: 2, time: 1800 });
                 }
               },
               error: function(error) {
                 layer.msg("删除失败，请稍后重试", { icon: 2, time: 1800 });
               }
             });
             layer.close(index);
           });
         });
         $("[name='addressbox']").append($item);}
      if (data.length < 6) {
        let itemtext = $("#addAddress").text();
        let $item = $(itemtext);
        $("[name='addressbox']").append($item);
      }
      form.render('checkbox');
    }
  });
  }



  form.on('checkbox(defaultAddress)', function(data) {
    // 获取所有复选框
    const checkboxes = $("[name='default']");
    checkboxes.prop("checked", false); // 取消所有选中状态
    data.elem.checked = true; // 仅保留当前选中项
    form.render('checkbox'); // 重新渲染

    const addressid = data.elem.getAttribute("_addrid");
    console.log('传递的 addressid:', addressid); // 打印参数检查
    // 更新数据库
    $.ajax({
      url: 'address/setdefault',
      data: { addressid: addressid },
      success: function(response) {
        console.log("addresssetdefault",response);
        if (response.code===200 ) {
          layer.msg("默认地址已更新", { icon: 1 });
          showAddress(); // 刷新列表
        } else {
          layer.msg("更新默认地址失败，请稍后重试", { icon: 2 });
          // 恢复复选框状态
          data.elem.checked = false;
          form.render('checkbox');
        }
      },
    });
  });
  // 编辑地址功能
  $("[name='addressbox']").on("click", "button[name='edit']", function () {
    const addressid = $(this).attr("_addrid");

    // 获取用户的所有地址信息
    $.ajax({
      url: "address/getaddressbyuserid",
      success: function (result) {
        console.log('要编辑的地址 ID:', result); // 打印地址 ID 进行检查
        if (result.code === 200) {
          const addresses = result.data;
          console.log('获取到的地址数据:', addresses); // 打印地址数据进行检查
          // 筛选出要编辑的地址
          const addressToEdit = addresses.find(address => address.addressid == addressid);
          if (addressToEdit) {
            // 填充表单
            form.val("addAddressWin", {
              addressname: addressToEdit.addressname,
              provincecode: addressToEdit.provincecode,
              province: addressToEdit.province,
              citycode: addressToEdit.citycode,
              city: addressToEdit.city,
              areacode: addressToEdit.areacode,
              area: addressToEdit.area,
              address: addressToEdit.address,
              name: addressToEdit.name,
              phone: addressToEdit.phone
            });
            // 显示弹窗
            editAddressLayerIndex = layer.open({
              type: 1,
              area: ["400px", "600px"],
              content: $("#addAddressWin"),
              success: function () {
                // 触发省份选择事件，更新城市和区划下拉框
                form.val("addAddressWin", { provincecode: addressToEdit.provincecode });
                form.render('select', 'addAddressWin');
                form.on('select(provincecode)', function (data) {
                  let provincecode = data.value; // 得到被选中的值
                  showArea(provincecode, $("[name='citycode']"));
                  let provincename = $(data.othis).find("input").val();
                  $("[name='province']").val(provincename);
                });
                // 触发城市选择事件，更新区划下拉框
                form.val("addAddressWin", { citycode: addressToEdit.citycode });
                form.render('select', 'addAddressWin');
                form.on('select(citycode)', function (data) {
                  let citycode = data.value; // 得到被选中的值
                  showArea(citycode, $("[name='areacode']"));
                  let cityname = $(data.othis).find("input").val();
                  $("[name='city']").val(cityname);
                });
              }
            });
            // 提交编辑后的地址信息
            form.on("submit(addAddressBtn)", function (obj) {
              let formdata = obj.field;
              formdata.addressid = addressid;
              $.ajax({
                url: 'address/edit',
                data: formdata,
                success: function (result) {
                  if (result.code === 200) {
                    layer.msg("编辑成功", { icon: 1, time: 1800 });
                    // 关闭弹窗
                    layer.close(editAddressLayerIndex);
                    // 重新加载地址列表
                    showAddress();
                  } else {
                    layer.msg("编辑失败，请稍后重试", { icon: 2, time: 1800 });
                  }
                },
                error: function (error) {
                  layer.msg("编辑失败，请稍后重试", { icon: 2, time: 1800 });
                }
              });
              return false;
            });
          } else {
            layer.msg("未找到要编辑的地址", { icon: 2, time: 1800 });
          }
        } else {
          layer.msg("获取地址信息失败，请稍后重试", { icon: 2, time: 1800 });
        }
      },
    });
  });

  //获取收藏商品的信息
  function showCollection() {
    $.ajax({
      url: 'collect/list',
      success: function (result) {
        console.log("获取收藏商品信息响应：", result);
        if (result.code === 200) {
          const data = result.data;
          const collectBox = $("[name='collectbox']");
          collectBox.empty();

          const template = $('#collect-item-template').text();
          const render = layui.laytpl(template);

          data.forEach(item => {
            const html = render.render(item);
            collectBox.append(html);
          });

          // 绑定取消收藏按钮点击事件
          collectBox.on('click', '.collect-item-delete', function (e) {
            e.stopPropagation();
            const productid = $(this).data('productid');
            layer.confirm('确定要取消收藏该商品吗？', {
              icon: 3,
              title: '确认取消收藏'
            }, function (index) {
              $.ajax({
                url: 'collect/delete',
                data: {
                  productId: productid
                },
                success: function (response) {
                  if (response.code === 200) {
                    layer.msg("取消收藏成功", { icon: 1, time: 1800 });
                    showCollection(); // 刷新收藏列表
                  } else {
                    layer.msg("取消收藏失败，请稍后重试", { icon: 2, time: 1800 });
                  }
                },
                error: function (error) {
                  layer.msg("取消收藏失败，请稍后重试", { icon: 2, time: 1800 });
                }
              });
              layer.close(index);
            });
          });

          // 为收藏项添加点击跳转事件
          collectBox.on('click', '.collect-item', function () {
            const productid = $(this).data('productid');
            window.location.href = `page/detail?productid=${productid}`;
          });
        } else {
          layer.msg("获取收藏商品信息失败，请稍后重试", { icon: 2, time: 1800 });
        }
      },
      error: function (error) {
        layer.msg("获取收藏商品信息失败，请稍后重试", { icon: 2, time: 1800 });
      }
    });
  }

  // 显示评价管理内容
  function showEvaluation() {
    // 根据 userid 获取评论信息
    $.ajax({
      url: 'comment/listByUserId',
      xhrFields: {
        withCredentials: true // 允许携带 cookie
      },
      crossDomain: true, // 允许跨域请求
      success: function (response) {
        if (response.code === 200) {
          const comments = response.data;
          const evaluationList = $('#evaluation-list');
          evaluationList.empty();

          if (comments.length === 0) {
            evaluationList.html('<p style="text-align: center;">暂无评论信息</p>');
            return;
          }

          comments.forEach(comment => {
            const ratingText = getRatingText(comment.type); // 根据 type 获取评价文本
            const html = `
                            <div class="comment-item">
                                <div class="comment-user">
                                    <img src="${comment.imgurl}" alt="${comment.username}" class="comment-user-avatar">
                                    <span class="comment-user-name">${comment.username}</span>
                                </div>
                                <p class="comment-rating">${ratingText}</p>
                                <p class="comment-content">${comment.text}</p>
                                <div class="comment-product">
                                    <img src="${comment.product.imgurl}" alt="${comment.product.productname}" class="comment-product-img" data-productid="${comment.product.productid}" style="cursor: pointer;">
                                    <span>商品名称: ${comment.product.productname}</span>
                                </div>
                                <p class="comment-addtime">评论时间: ${formatDate(comment.addtime)}</p>
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-danger delete-comment" data-commentid="${comment.commentid}">删除</button>
                            </div>
                        `;
            evaluationList.append(html);
          });

          // 绑定删除按钮的点击事件
          evaluationList.on('click', '.delete-comment', function () {
            const commentid = $(this).data('commentid');
            layer.confirm('确定要删除该评论吗？', {
              icon: 3,
              title: '确认删除'
            }, function (index) {
              $.ajax({
                url: 'comment/delete',
                data: { id: commentid },
                success: function (response) {
                  if (response.code === 200) {
                    layer.msg("删除成功", { icon: 1, time: 1800 });
                    showEvaluation(); // 刷新评论列表
                  } else {
                    layer.msg("删除失败，请稍后重试", { icon: 2, time: 1800 });
                  }
                },
                error: function (error) {
                  layer.msg("删除失败，请稍后重试", { icon: 2, time: 1800 });
                }
              });
              layer.close(index);
            });
          });

          // 绑定商品图片的点击事件
          evaluationList.on('click', '.comment-product-img', function () {
            const productid = $(this).data('productid');
            window.location.href = `page/detail?productid=${productid}`;
          });
        } else {
          layer.msg(response.msg, { icon: 2, time: 1800 });
        }
      },
      error: function (error) {
        layer.msg("获取评论信息失败，请稍后重试", { icon: 2, time: 1800 });
      }
    });
  }
  // 根据 type 获取评价文本
  function getRatingText(type) {
    switch (type) {
      case 1:
        return '好评';
      case 2:
        return '中评';
      case 3:
        return '差评';
      default:
        return '未知评价';
    }
  }

  // 格式化日期
  function formatDate(dateStr) {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  // 退出登录逻辑
  const logoutLink = document.getElementById('logoutLink');
  logoutLink.addEventListener('click', function (e) {
    e.preventDefault(); // 阻止默认的链接跳转行为
    // 弹出确认提示框
    if (confirm('确定要退出登录吗？')) {
      $.ajax({
        url: 'logout', // 后端退出登录的接口地址
        method: 'GET',
        success: function (response) {
          if (response.code === 200) {
            // 退出登录成功，给出提示并跳转到登录页面
            alert(response.msg);
            window.location.href = 'page/login';
          } else {
            // 退出登录失败，给出提示
            alert(response.msg);
          }
        },
        error: function (error) {
          console.error('退出登录失败:', error);
          alert('退出登录时发生错误，请稍后再试。');
        }
      });
    }
  });


</script>
</body>
</html>